package com.eric.service.impl;
import cn.dev33.satoken.util.SaResult;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.eric.domain.bso.ChildType;
import com.eric.domain.bso.TypeTree;
import com.eric.domain.dto.MaterialDto;
import com.eric.domain.dto.MaterialTypeDto;
import com.eric.domain.po.EquipType;
import com.eric.domain.po.Material;
import com.eric.domain.po.MaterialType;
import com.eric.mapper.MaterialTypeMapper;
import com.eric.service.ILocationService;
import com.eric.service.IMaterialTypeService;
import com.eric.utils.PublicTools;
import com.github.yulichang.base.MPJBaseServiceImpl;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import static com.eric.utils.Constant.PAGE_CURRENT;
import static com.eric.utils.Constant.PAGE_SIZE;

/**
 * <p>
 * 材料类型 服务实现类
 * </p>
 *
 * @author 新哥
 * @since 2024-04-26
 */
@Service
@Transactional
@RequiredArgsConstructor
public class MaterialTypeServiceImpl extends MPJBaseServiceImpl<MaterialTypeMapper, MaterialType> implements IMaterialTypeService {
    private final ILocationService locationService;
    @Override
    public SaResult saveOneMaterialTypeService(MaterialTypeDto materialTypeDto) {
        if (BeanUtil.isEmpty(materialTypeDto)) {
            return SaResult.error("对象不能为空");
        }

        MaterialTypeDto materialTypeDtoChecked = checkedObjStr(materialTypeDto);

        if (StrUtil.isBlank(materialTypeDtoChecked.getParentType())) {
            return SaResult.error("一级分类名称不能为空");
        }
        if (StrUtil.isBlank(materialTypeDtoChecked.getChildType())){
            return SaResult.error("二级分类名称不能为空");
        }

        MPJLambdaWrapper<MaterialType> wrapper = new MPJLambdaWrapper<MaterialType>()
                .eq("parent_type", materialTypeDtoChecked.getParentType())
                .eq("child_type", materialTypeDtoChecked.getChildType());
        MaterialType materialType = getOne(wrapper);
        if (!BeanUtil.isEmpty(materialType)) {
            return SaResult.error("已存在数据");
        }
        String parentType = materialTypeDtoChecked.getParentType();
        String childType = materialTypeDtoChecked.getChildType();
        String fullName=parentType+":"+childType;
        materialTypeDtoChecked.setFullName(fullName);
        save(BeanUtil.copyProperties(materialTypeDtoChecked, MaterialType.class));
        return SaResult.ok();
    }

    @Override
    public SaResult modifyOneService(MaterialTypeDto materialTypeDto) {
        if (BeanUtil.isEmpty(materialTypeDto)) {
            return SaResult.error("对象不能为空");
        }
        MaterialTypeDto materialTypeDtoChecked = checkedObjStr(materialTypeDto);
//       获取到需要修改的数据行的id
        Integer id = materialTypeDtoChecked.getId();
//        根据id查询数据库中完整的数据---dto数据有些字段可能是null）
        MaterialType materialType = query().eq("id", id).one();
        String parentType;
        String childType;

        if (materialTypeDtoChecked.getParentType() == null&&materialTypeDtoChecked.getChildType()==null) {
            String typeParentType = materialType.getParentType();
            String typeChildType = materialType.getChildType();
            String fullName=typeParentType+":"+typeChildType;
            materialTypeDtoChecked.setFullName(fullName);
            updateById(BeanUtil.copyProperties(materialTypeDtoChecked, MaterialType.class));
            return SaResult.ok();
        }

//        判断equipTypeDtoChecked中两个字段，parentType,childType
        if (materialTypeDtoChecked.getParentType()==null){
            parentType=materialType.getParentType();
        }
        else {
            parentType=materialTypeDtoChecked.getParentType();
        }

        if (materialTypeDtoChecked.getChildType()==null){
            childType=materialType.getChildType();
        }
        else {
            childType=materialTypeDtoChecked.getChildType();
        }

//        通过自定义的typeDto中字段，查询数据库中有没有存在相同的对象
        MPJLambdaWrapper<MaterialType>wrapper=new MPJLambdaWrapper<MaterialType>()
                .eq("parent_type",parentType)
                .eq("child_type", childType);
        MaterialType one = getOne(wrapper);

        if (!BeanUtil.isEmpty(one)) {
            materialTypeDtoChecked.setParentType(null);
            materialTypeDtoChecked.setChildType(null);
            materialTypeDtoChecked.setFullName(null);
            updateById(BeanUtil.copyProperties(materialTypeDtoChecked, MaterialType.class));
            return SaResult.ok("修改成功！");
        }

        String fullName=parentType+":"+childType;
        materialTypeDtoChecked.setFullName(fullName);
        updateById(BeanUtil.copyProperties(materialTypeDtoChecked, MaterialType.class));
        return SaResult.ok("succeed!");
    }

    @Override
    public SaResult getAllService(Integer current,Integer pageSize) {
        if (current==null){
            current= PAGE_CURRENT;
        }
        if (pageSize==null){
            pageSize=PAGE_SIZE;
        }
        Page<MaterialType>page=new Page<>(current,pageSize);
        List<MaterialType> materialTypeList = query().page(page).getRecords();
        List<TypeTree> materialTypeTree = getMaterialTypeTree(materialTypeList);

        return SaResult.data(materialTypeTree);
    }

    @Override
    public SaResult getByNameService(String parentType,Integer current,Integer pageSize) {
        if (current==null){
            current= PAGE_CURRENT;
        }
        if (pageSize==null){
            pageSize=PAGE_SIZE;
        }

        Page<MaterialType>page=new Page<>(current,pageSize);
        List<MaterialType> materialTypeList = query().like("parent_type", parentType).page(page).getRecords();
        return SaResult.data(BeanUtil.copyToList(materialTypeList,MaterialTypeDto.class));
    }

    @Override
    public SaResult getByFullName(String parentType, String childType,Integer current,Integer pageSize) {
        if (current==null){
            current= PAGE_CURRENT;
        }
        if (pageSize==null){
            pageSize=PAGE_SIZE;
        }
        Page<MaterialType>page=new Page<>(current,pageSize);

        List<MaterialType> materialTypeList = query().like("parent_type", parentType)
                .like("child_type", childType)
                .page(page).getRecords();

        return SaResult.data(BeanUtil.copyToList(materialTypeList,MaterialTypeDto.class));
    }

    @Override
    public SaResult deleteByIdService(Integer id) {
        if (id==null){
            return SaResult.error("id不符合要求！");
        }
        removeById(id);
        return SaResult.ok("succeed!");
    }

    //    获取所有的材料类型，包括一级和二级分类
    @Override
    public SaResult getAllMaterialTypeService(Integer current,Integer pageSize) {
        if (current==null||current<=0){
            current = PAGE_CURRENT;
        }
        if (pageSize==null||pageSize<=0){
            pageSize = PAGE_SIZE;
        }
        String locationAddress = locationService.getAllByLoginId();

        if (StrUtil.isBlank(locationAddress)) {
            return SaResult.error("当前用户没有分配项目或者仓库地址");
        }

        Page<MaterialTypeDto>page=new Page<>(current,pageSize);
        page.setSize(pageSize);
        page.setCurrent(current);
        page.setOptimizeCountSql(false);
        MPJLambdaWrapper<MaterialType>wrapper=new MPJLambdaWrapper<MaterialType>()
                .selectAll(MaterialType.class);
        Page<MaterialTypeDto> materialTypeDtoPage = selectJoinListPage(page, MaterialTypeDto.class, wrapper);
        List<MaterialTypeDto> materialTypeDtoList = materialTypeDtoPage.getRecords();
        System.out.println(materialTypeDtoList);
        return SaResult.data(materialTypeDtoList);
    }

    @Override
    public SaResult getAllMaterialTypeCountService() {
        String locationAddress = locationService.getAllByLoginId();
        if (StrUtil.isBlank(locationAddress)) {
            return SaResult.error("当前用户没有分配项目或者仓库地址");
        }
        MPJLambdaWrapper<MaterialType>wrapper=new MPJLambdaWrapper<MaterialType>()
                .select("count(id)");
//                .eq(PublicTools.checkLoginRole(), Material::getLocation, locationAddress);
        Long l = selectJoinOne(Long.class,wrapper);

        return SaResult.data(l);
    }


    @Override
    public SaResult getByIdService(Integer id) {
        String locationAddress = locationService.getAllByLoginId();
        MPJLambdaWrapper<MaterialType>wrapper=new MPJLambdaWrapper<MaterialType>()
                .eq(!PublicTools.checkLoginRole(), Material::getLocation, locationAddress)
                .eq("id",id);
        MaterialTypeDto materialTypeDto = selectJoinOne(MaterialTypeDto.class, wrapper);
        if (!BeanUtil.isEmpty(materialTypeDto)) {
            return SaResult.data(materialTypeDto);
        }
        else {
            return SaResult.error("数据库中没有查询到数据");
        }
    }

    private MaterialTypeDto checkedObjStr(MaterialTypeDto materialTypeDto){

        String parentType = StrUtil.trim(materialTypeDto.getParentType());
        if (StrUtil.isBlank(parentType)){
            materialTypeDto.setParentType(null);
        }
        else {
            materialTypeDto.setParentType(parentType);
        }

        String childType = StrUtil.trim(materialTypeDto.getChildType());
        if (StrUtil.isBlank(childType)){
            materialTypeDto.setChildType(null);
        }
        else {
            materialTypeDto.setChildType(childType);
        }

        String description = StrUtil.trim(materialTypeDto.getDescription());
        if (StrUtil.isBlank(description)){
            materialTypeDto.setDescription(null);
        }

        return materialTypeDto;
    }

    private List<TypeTree>getMaterialTypeTree(List<MaterialType>materialTypeList){
        List<MaterialTypeDto> materialTypeDtoList=BeanUtil.copyToList(materialTypeList,MaterialTypeDto.class);
        Set<String>materialParentStr=new HashSet<>();
        Set<String>materialChildStr=new HashSet<>();
        List<TypeTree>typeTreeList=new ArrayList<>();
        for (MaterialTypeDto materialTypeDto : materialTypeDtoList) {
            materialParentStr.add(materialTypeDto.getParentType());
            materialChildStr.add(materialTypeDto.getChildType());
        }

        for (String materialParentType : materialParentStr) {
            TypeTree typeTree=new TypeTree();

            typeTree.setValue(materialParentType);
            typeTree.setLabel(materialParentType);
            typeTreeList.add(typeTree);
        }

        //        遍历equipTreeBsoList
        for (TypeTree typeTree : typeTreeList) {
//            创建一个String类型的List
            List<ChildType>childTypeStr=new ArrayList<>();
//            遍历前端传进来的EquipType
            for (MaterialType materialType : materialTypeList) {
                ChildType childType =new ChildType();
//                如果equipType中的ParentType和equipTreeBso中的parentType一致
                if (materialType.getParentType().equals(typeTree.getValue())){
                    childType.setValue(materialType.getChildType());
                    childType.setLabel(materialType.getChildType());
//                    childTypeStr增加一个childType
                    childTypeStr.add(childType);
                }
            }
//            把获取到的childTypeList放到EquipTreeBso中
            typeTree.setChildren(childTypeStr);
        }
        return typeTreeList;
    }
}
